package com.example.demo.netty.server;

import com.example.demo.config.NettyServerConfig;
import com.example.demo.netty.protocol.coder.data.PacketDecoder;
import com.example.demo.netty.server.handler.modBusDataHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

/**
 * @ClassName NettyServer
 * @Description
 * @Company inspur
 * @Author Kevin
 * @Date 2020/6/18 22:42
 * @Version 1.0
 */
@Component
@Slf4j
public class NettyServer {
    @Autowired
    NettyServerConfig serverConfig;

    NioEventLoopGroup bossGroup = new NioEventLoopGroup();
    NioEventLoopGroup workerGroup = new NioEventLoopGroup();
    ServerBootstrap serverBootstrap;
    ChannelFuture f;

    /**
     * 启动Netty服务
     * @throws InterruptedException
     */
    @PostConstruct
    public void start() throws InterruptedException {
        serverBootstrap = new ServerBootstrap();
        serverBootstrap
                .group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) {
                        ch.pipeline().addLast(new PacketDecoder());
                        ch.pipeline().addLast(new modBusDataHandler());
//                        ch.pipeline().addLast(new StringDecoder());
//                        ch.pipeline().addLast(new SimpleChannelInboundHandler<String>() {
//                            @Override
//                            protected void channelRead0(ChannelHandlerContext ctx, String msg) {
//                                System.out.println(msg);
//                            }
//                        });
                    }
                });
        Integer port = Integer.valueOf(serverConfig.getPort().trim());
        // Start the Server 8000
        f = serverBootstrap.bind(port).sync();
        log.info("启动 Netty 成功！");
    }

    @PreDestroy
    public void destroy() throws InterruptedException {
        // Wait Util the server socket is closed
        f.channel().closeFuture().sync();
        bossGroup.shutdownGracefully().syncUninterruptibly();
        workerGroup.shutdownGracefully().syncUninterruptibly();
        log.info("关闭 Netty 成功");
    }
}
